const { mergeAgent, logger, cloudApiClient } = require('../utils');
const UserService = require('../service/user');

const userService = new UserService();


module.exports = (app) => {
  // 跳转外部链接
  app.post(`${process.env.VUE_APP_BASE_API}/external/detail`, async (req, res) => {
    const { body, headers } = req;
    const token = headers['x-token'];
    const { Module, ModuleId, MenuStatus = 'ENABLE' } = body;
    const targetUser = await userService.resolveToken(token);
    let params = {};
    if (targetUser) {
      params = {
        Agent: mergeAgent({
          ProxyOrganizationOpenId: targetUser.organizationOpenId,
          OpenId: targetUser.openId,
        }),
        ProxyOrganizationName: targetUser.organizationName,
        ProxyOperatorName: targetUser.userName,
        Module,
        ModuleId,
        UniformSocialCreditCode: targetUser.uniformSocialCreditCode,
        Endpoint: 'PC',
        MenuStatus,
      };
    }

    cloudApiClient.CreateConsoleLoginUrl(params).then(
      (data) => {
        if (data.ConsoleUrl) {
          return res.json({
            code: 20000,
            data,
          });
        }
        return res.json(data);
      },
      (err) => {
        logger.error({
          ...params,
          Action: 'CreateConsoleLoginUrl',
          message: err,
        });
        res.json({
          code: 500,
          err,
        });
      },
    );
  });

  // 印章列表
  app.post(`${process.env.VUE_APP_BASE_API}/seal/list`, async (req, res) => {
    const { headers = {}, body } = req;
    const token = headers['x-token'];
    const targetUser = await userService.resolveToken(token);

    if (targetUser) {
      const params = {
        Agent: mergeAgent({
          ProxyOrganizationOpenId: targetUser.organizationId,
          OpenId: targetUser.openId,
        }),
        ...body,
      };
      cloudApiClient.ChannelDescribeOrganizationSeals(params).then(
        (data) => {
          res.json({
            code: 20000,
            data,
          });
        },
        (err) => {
          logger.error({
            ...params,
            Action: 'ChannelDescribeOrganizationSeals',
            message: err,
          });
          res.json(err);
        },
      );
    } else {
      logger.error({
        Action: 'seal/list',
        token,
        message: '用户信息不存在',
      });
      res.json({
        code: 500,
        message: '用户信息不存在',
      });
    }
  });
};
